package com.coupon.distribution.serialization;

import com.alibaba.fastjson.JSON;
import com.coupon.distribution.entity.Coupon;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @author 王哲
 * @Contact 1121586359@qq.com
 * @ClassName CouponSerialize.java
 * @create 2023年06月26日 上午10:00
 * @Description 优惠券实体类自定义序列化器
 * @Version V1.0
 */
public class CouponSerialize extends JsonSerializer<Coupon> {
    @Override
    public void serialize(Coupon coupon,
                          JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider)
            throws IOException {

        // 开始序列化
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("id", coupon.getId().toString());
        jsonGenerator.writeStringField("templateId",
                coupon.getTemplateId().toString());
        jsonGenerator.writeStringField("userId",
                coupon.getUserId().toString());
        jsonGenerator.writeStringField("couponCode",
                coupon.getCouponCode());
        jsonGenerator.writeStringField("assignTime",
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(
                        coupon.getAssignTime()
                ));

        jsonGenerator.writeStringField("name",
                coupon.getCouponTemplateSDK().getName());
        jsonGenerator.writeStringField("logo",
                coupon.getCouponTemplateSDK().getLogo());
        jsonGenerator.writeStringField("desc",
                coupon.getCouponTemplateSDK().getDesc());
        jsonGenerator.writeStringField("expiration",
                JSON.toJSONString(
                        coupon.getCouponTemplateSDK().getRule().getExpiration()
                ));
        jsonGenerator.writeStringField("discount",
                JSON.toJSONString(
                        coupon.getCouponTemplateSDK().getRule().getDiscount()
                ));
        jsonGenerator.writeStringField("usage",
                JSON.toJSONString(coupon.getCouponTemplateSDK().getRule().getUsage()));

        jsonGenerator.writeEndObject();
    }
}
